/**
 * ajax封装
 */
window.ajax = function (obj) {
    let $ = layui.jquery;
    $.ajax({
        url: obj.url || '',
        data: obj.data || {},
        type: obj.type || 'GET',
        dataType: 'json',
        success: function (resp) {
            if (resp.code === 200) {
                obj.success && obj.success(resp);
            } else {
                layer.closeAll('loading');
                if(obj.error){
                    obj.error && obj.error(resp.msg);
                }else{
                    layer.msg(resp.msg || '出现错误', {icon: 2})
                }
            }
        },
        error: function (e) {
            if(obj.error){
                obj.error && obj.error(e);
            }else{
                layer.msg('出现未知错误', {icon: 2})
            }
        }
    })
};


!(function () {
    let Utils = {

        /**
         * 渲染XmSelect
         * @param options
         */
        renderXmSelect: function (options) {
            let $ = layui.jquery;
            if (!Array.isArray(options)){
                options = [options];
            }

            for (let i = 0; i < options.length; i++) {
                let defaults = {
                    ele: "",
                    tips: "请选择",
                    remoteUrl: "",
                    echoUrl: "",
                    radio: false,
                    autoRow: true,
                    paging: true,
                    filterable: true,
                    pageRemote: true,
                    remoteSearch: true,
                    pageSize: 8,
                    name: "select", // 提交到服务器的key
                    layVerify: "",
                    layVerType: "",
                    layReqText: "",
                    direction: "down",
                    field: {
                        value: "id",
                        name: "name",
                    }
                };
                let settings = $.extend(true,{},defaults,options[i]);

                let tempSelect = xmSelect.render({
                    el: settings.ele,
                    tips: settings.tips,
                    radio: settings.radio,
                    clickClose: !!settings.radio,
                    autoRow: settings.autoRow,
                    paging: settings.paging,
                    filterable: settings.filterable,
                    pageRemote: settings.pageRemote,
                    pageEmptyShow: true, //  无数据不展示分页
                    remoteSearch: settings.remoteSearch,
                    pageSize: settings.pageSize,
                    name: settings.name,
                    layVerify: settings.layVerify,
                    layVerType: settings.layVerType,
                    layReqText: settings.layReqText,
                    direction: settings.direction,
                    remoteMethod: function(val, callback, show, pageIndex){
                        //val: 搜索框的内容, 不开启搜索默认为空, cb: 回调函数, show: 当前下拉框是否展开, pageIndex: 当前第几页
                        $.ajax({
                            method: 'get',
                            url:  settings.remoteUrl,
                            data: {
                                search: val,
                                page: pageIndex,
                                limit: settings.pageSize
                            }
                        }).then(response => {
                            // 处理服务器返回的数据
                            if(response.data){
                                let result = [];
                                response.data.map(function (item) {
                                    let row = {"value": item[settings.field.value], "name": item[settings.field.name]};
                                    // if (selectedList.indexOf(row.value) >= 0) {
                                    //     row['selected'] = true;
                                    // }
                                    result.push(row);
                                });
                                callback(result, Math.floor((response.count - 1)/settings.pageSize) + 1)
                            }
                        })
                    },
                });

                // 获取当前的值
                if(settings.value){
                    settings.value = settings.value.toString();
                    // 数据回显
                    $.ajax({
                        method: 'get',
                        url:  settings.echoUrl,
                        data: {
                            ids: settings.value,
                        }
                    }).then(response => {
                        // 处理服务器返回的数据
                        if(response.data){
                            let selectedList = [];
                            response.data.map(function (item) {
                                let row = {"value": item[settings.field.value], "name": item[settings.field.name]};
                                selectedList.push(row);
                            });
                            tempSelect.setValue(selectedList);
                        }
                    })
                }
            }
        },

        /**
         * 渲染XmTree
         * @param options
         */
        renderXmTree: function (options){
            let $ = layui.jquery;
            if (!Array.isArray(options)){
                options = [options];
            }

            for (let i = 0; i < options.length; i++) {
                let defaults = {
                    ele: "",
                    remoteUrl: "",
                    tips: "请选择",
                    name: "select", // 提交到服务器的key
                    value: "",      // 选择的值
                    layVerify: "",
                    layVerType: "",
                    layReqText: "",
                    direction: "down", // 下拉方向
                    radio: false,
                    treeStrict: true,
                    field: {
                        value: "id",
                        name: "title",
                    },
                };
                let settings = $.extend(true,{},defaults,options[i]);

                // 获取当前的值
                let selectedList = [];
                if (settings.value.length > 1){
                    selectedList = settings.value.split(",").map(function (v) {
                        parseInt(v);
                    });
                }else {
                    selectedList.push(parseInt(settings.value));
                }

                $.ajax({
                    method: 'get',
                    url:  settings.remoteUrl,
                }).done(response => {
                    // 处理服务器返回的数据
                    let treeData = response.data;

                    // 递归处理
                    let recursive = function (arr) {
                        arr.map(function (item) {
                            item["name"] = item[settings.field.name];
                            item["value"] = item[settings.field.value];
                            // 处理选择的值
                            if (selectedList.indexOf(item.value) >= 0) {
                                item['selected'] = true;
                            }
                            if(item.children !== undefined && item.children.length > 0){
                                recursive(item.children);
                            }
                        })
                    };
                    recursive(treeData);

                    xmSelect.render({
                        el: settings.ele,
                        autoRow: true,
                        filterable: false,
                        tips: settings.tips,
                        name: settings.name,
                        value: settings.value,
                        layVerify: settings.layVerify,
                        layVerType: settings.layVerType,
                        layReqText: settings.layReqText,
                        direction: settings.direction,
                        radio: settings.radio,
                        clickClose: !!settings.radio,
                        tree: {
                            show: true,
                            showFolderIcon: true,
                            showLine: false,
                            indent: 20,
                            expandedKeys: true,
                            strict: settings.treeStrict,
                        },
                        toolbar: {
                            show: false,
                            list: []
                        },
                        height: 'auto',
                        data: function(){
                            return treeData;
                        }
                    })

                });
            }
        },

        /**
         * 表单参数处理
         * @param options
         */
        processFormParams: function (options){
            let $ = layui.jquery;
            let settings = {};
            if(typeof options !== "object"){
                settings = {"ele": options};
            }else {
                settings = options;
            }

            let array = $(settings.ele).serializeArray();
            let params = {};
            $.each(array, function() {
                if (params[this.name] !== undefined) {
                    params[this.name] = params[this.name] + ',' + this.value
                } else {
                    params[this.name] = this.value || '';
                }
            });
            return params;
        },


        /**
         * 表单元素渲染
         * @param laDom
         */
        formRender: function (laDom) {
            let $ = layui.jquery;
            let laydate = layui.laydate;

            // 下拉选择框
            let singleSelect = laDom.find(".single-select");
            let multipleSelect = laDom.find(".multiple-select");
            let options = [];
            $.each(singleSelect, function () {
                let name = $(this).data("name");
                let label = $(this).data("label");
                let verify = $(this).data("verify");
                let url = $(this).data("url");
                let value = $(this).data("value");
                let echo = $(this).data("echo");
                options.push({
                    ele: "#" + name,
                    name: name,
                    value: value,
                    echoUrl: echo,
                    tips: "请选择" + label,
                    layVerify: verify,
                    layReqText: label + "不能为空",
                    remoteUrl: url,
                    radio: true
                })
            });
            $.each(multipleSelect, function () {
                let name = $(this).data("name");
                let label = $(this).data("label");
                let verify = $(this).data("verify");
                let url = $(this).data("url");
                let value = $(this).data("value");
                let echo = $(this).data("echo");
                options.push({
                    ele: "#" + name,
                    name: name,
                    value: value,
                    echoUrl: echo,
                    tips: "请选择" + label,
                    layVerify: verify,
                    layReqText: label + "不能为空",
                    remoteUrl: url,
                    radio: false,
                })
            });

            this.renderXmSelect(options);

            // 下拉选择树
            let options2 = [];
            let singleTreeSelect = laDom.find(".single-tree-select");
            let multipleTreeSelect = laDom.find(".multiple-tree-select");
            $.each(singleTreeSelect, function () {
                let name = $(this).data("name");
                let label = $(this).data("label");
                let verify = $(this).data("verify");
                let url = $(this).data("url");
                let value = $(this).data("value");
                options2.push({
                    ele: "#" + name,
                    name: name,
                    value: value,
                    tips: "请选择" + label,
                    layVerify: verify,
                    layReqText: label + "不能为空",
                    remoteUrl: url,
                    radio: true,
                    treeStrict: false
                })
            });
            $.each(multipleTreeSelect, function () {
                let name = $(this).data("name");
                let label = $(this).data("label");
                let verify = $(this).data("verify");
                let url = $(this).data("url");
                let value = $(this).data("value");
                options2.push({
                    ele: "#" + name,
                    name: name,
                    value: value,
                    tips: "请选择" + label,
                    layVerify: verify,
                    layReqText: label + "不能为空",
                    remoteUrl: url,
                    radio: false,
                    treeStrict: true
                })
            });
            this.renderXmTree(options2);

            // 渲染日期
            let layuiDate = laDom.find(".layui-date");
            $.each(layuiDate, function () {
                let name = $(this).attr("name");
                let format = $(this).attr("format");
                let range = $(this).attr("range");
                laydate.render({
                    elem: '#' + name,
                    type: format,
                    range: range === 'true'
                });
            });

            // 渲染表单
            layui.form.render();
        },

        /**
         * 触发表单提交
         * @param options
         */
        formSubmit: function (options) {
            let $ = layui.jquery;
            let settings = {};
            if(typeof options !== "object"){
                settings = {"ele": options};
            }else {
                settings = options;
            }
            // 触发表表单提交
            $(settings.ele).find('*[type="submit"]').trigger("click");
        }

    };
    window.UTILS = Utils;
})();

